package com.lzm.ydpt.module.mall.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.byt.framlib.base.BaseFragment;
import com.byt.framlib.baseadapter.lv.LvCommonAdapter;
import com.byt.framlib.baseadapter.lv.LvViewHolder;
import com.byt.framlib.baseadapter.rv.RvCommonAdapter;
import com.byt.framlib.baseadapter.rv.RvViewHolder;
import com.byt.framlib.basemvp.basebean.ListPageBean;
import com.byt.framlib.basemvp.boby.FormBodys;
import com.byt.framlib.commonutils.image.ImageLoaderUtils;
import com.byt.framlib.commonutils.rx.RxBus;
import com.byt.framlib.commonwidget.LoadingTip;
import com.byt.framlib.commonwidget.NoScrollListview;
import com.byt.framlib.commonwidget.OnNoDoubleClickListener;
import com.byt.framlib.commonwidget.RoundedConnerImageView;
import com.byt.framlib.commonwidget.refresh.RefreshHeaderView;
import com.byt.framlib.commonwidget.selectordialog.dialog.DialogOnClickListener;
import com.byt.framlib.commonwidget.selectordialog.dialog.NormalAlertDialog;
import com.lzm.ydpt.BaseColor;
import com.lzm.ydpt.Constants;
import com.lzm.ydpt.R;
import com.lzm.ydpt.entity.mall.MallOrderBean;
import com.lzm.ydpt.entity.mall.MallOrderListBus;
import com.lzm.ydpt.entity.mall.ShopGoods;
import com.lzm.ydpt.module.mall.activity.LogisticsDetailsActivity;
import com.lzm.ydpt.module.mall.activity.MallOrderDetailsActivity;
import com.lzm.ydpt.module.mall.activity.PayOrderActivity;
import com.lzm.ydpt.module.mall.utils.ProductUtil;
import com.lzm.ydpt.mvp.contract.MallOrderListContract;
import com.lzm.ydpt.mvp.presenterimpl.MallOrderListPresenterImpl;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 订单列表
 */
public class MallOrderListFragment extends BaseFragment<MallOrderListPresenterImpl> implements MallOrderListContract.View {

    public static final String INP_MY_ORDER_STATE = "MY_ORDER_STATE";

    @BindView(R.id.ltip_mall_order)
    LoadingTip ltip_mall_order;
    @BindView(R.id.rv_mall_order)
    RecyclerView rv_mall_order;
    @BindView(R.id.srl_mall_order)
    RefreshLayout srl_mall_order;

    private int pageNum = 1;
    private List<MallOrderBean> mOrder = new ArrayList<>();
    private RvCommonAdapter<MallOrderBean> mRvOrderAdapter;

    private static MallOrderListFragment mFragment = null;

    /**
     * 0.全部 1:待付款，2:已取消，3:已关闭，4：待发货（用户付款后），5：待领取，6：待配送，7：待收货，8：已配送 9:已发货，10：完成
     */
    private int order_state = 0;

    public static MallOrderListFragment newInstance(int type) {
        Bundle bundle = new Bundle();
        bundle.putInt(INP_MY_ORDER_STATE, type);
        mFragment = new MallOrderListFragment();
        mFragment.setArguments(bundle);
        return mFragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_mall_order_list;
    }

    @Override
    public MallOrderListPresenterImpl initPresenter() {
        return new MallOrderListPresenterImpl(this);
    }

    @Override
    protected void initView() {
        order_state = getArguments().getInt(INP_MY_ORDER_STATE, 0);
        initRv();
        initAdapter();
        addSubscription(RxBus.getDefault().toObservableSticky(MallOrderListBus.class).subscribe(
                orderStatueEvent -> {
                    pageNum = 1;
                    fetchOrderList();
                }));
    }

    @Override
    public void initFristData() {
        super.initFristData();
        ltip_mall_order.setLoadingTip(LoadingTip.LoadStatus.loading);
        pageNum = 1;
        fetchOrderList();
    }

    private void initAdapter() {
        rv_mall_order.setLayoutManager(new LinearLayoutManager(context));
        mRvOrderAdapter = new RvCommonAdapter<MallOrderBean>(context, mOrder, R.layout.item_mall_order_list) {
            @Override
            protected void convert(RvViewHolder viewHolder, MallOrderBean orderBean, int position) {
                // 1:待付款 2:已取消 3:已关闭 4：待发货（用户付款后）5：待领取 6：待配送 7：待收货 8：已配送 9:已发货 10：完成
                // 3 4 5 6 7 8 9 10 可以显示售后状态
                viewHolder.setText(R.id.tv_order_store_name, orderBean.getStore_name());
                NoScrollListview nolv_order_product_list = viewHolder.getView(R.id.nolv_order_product_list);
                if (orderBean.getGoods() != null && orderBean.getGoods().size() > 0) {
                    nolv_order_product_list.setVisibility(View.VISIBLE);
                    nolv_order_product_list.setAdapter(new LvCommonAdapter<ShopGoods>(context, orderBean.getGoods(), R.layout.item_mall_order_product) {
                        @Override
                        protected void convert(LvViewHolder holder, ShopGoods item, int position) {
                            RoundedConnerImageView img_order_product_pic = holder.getView(R.id.img_order_product_pic);
                            ImageLoaderUtils.display(img_order_product_pic, item.getImage_src());
                            holder.setText(R.id.tv_order_product_name, item.getTitle());
                            holder.setText(R.id.tv_order_product_sku, item.getSpec_title());
                            holder.setText(R.id.tv_order_product_sku_num, "x" + item.getTotal());
                            holder.setText(R.id.tv_order_product_price, "合计：¥" + item.getPrice_rmb());
                            TextView tv_order_product_state_back = holder.getView(R.id.tv_order_product_state_back);
                            if (item.getRefund_state() > 0 && item.getRefund_state() != 3) {
                                tv_order_product_state_back.setVisibility(View.VISIBLE);
                                tv_order_product_state_back.setText(ProductUtil.showRefundState(item.getRefund_state()));
                            } else {
                                tv_order_product_state_back.setVisibility(View.GONE);
                            }
                            tv_order_product_state_back.setOnClickListener(new OnNoDoubleClickListener() {
                                @Override
                                protected void onNoDoubleClick(View v) {
                                    if (item.getOrder_refund_id() > 0) {
//                                        Bundle bundle = new Bundle();
//                                        bundle.putLong(Constants.INP_ORDER_REFUND_ID, item.getOrder_refund_id());
//                                        openActivity(SaleServiceDetailActivity.class, bundle);
                                    }
                                }
                            });
                            holder.getConvertView().setOnClickListener(new OnNoDoubleClickListener() {
                                @Override
                                protected void onNoDoubleClick(View v) {
                                    Bundle orderDetails = new Bundle();
                                    orderDetails.putLong(Constants.INP_ORDER_ID, orderBean.getOrder_id());
                                    openActivity(MallOrderDetailsActivity.class, orderDetails);
                                }
                            });
                        }
                    });
                } else {
                    nolv_order_product_list.setVisibility(View.GONE);
                }
                viewHolder.setText(R.id.tv_order_price, "合计：¥" + orderBean.getAmount_rmb());
                int count = 0;
                for (int i = 0; i < orderBean.getGoods().size(); i++) {
                    count = count + orderBean.getGoods().get(i).getTotal();
                }
                viewHolder.setText(R.id.tv_order_product_count, "共" + count + "件商品 小计：");
                TextView tv_order_pay_state = viewHolder.getView(R.id.tv_order_pay_state);
                TextView tv_order_state_back = viewHolder.getView(R.id.tv_order_state_back);
                TextView tv_order_list_delete = viewHolder.getView(R.id.tv_order_list_delete);
                TextView tv_order_list_logistic = viewHolder.getView(R.id.tv_order_list_logistic);
                TextView tv_order_list_pay = viewHolder.getView(R.id.tv_order_list_pay);
                LinearLayout ll_show_opera_data = viewHolder.getView(R.id.ll_show_opera_data);
                switch (orderBean.getState()) {
                    case 1: //待付款
                        tv_order_pay_state.setVisibility(View.VISIBLE);
                        tv_order_pay_state.setText("待付款");
                        tv_order_pay_state.setTextColor(BaseColor.color_main);
                        tv_order_state_back.setVisibility(View.GONE);
                        tv_order_list_delete.setVisibility(View.GONE);
                        tv_order_list_logistic.setVisibility(View.GONE);
                        tv_order_list_pay.setVisibility(View.VISIBLE);
                        tv_order_list_pay.setText("去支付");
                        ll_show_opera_data.setVisibility(View.VISIBLE);
                        break;
                    case 2: // 取消
                    case 3: // 已关闭
                        tv_order_pay_state.setVisibility(View.VISIBLE);
                        tv_order_pay_state.setText(orderBean.getState() == 2 ? "已取消" : "已关闭");
                        tv_order_pay_state.setTextColor(BaseColor.color_666666);
                        // 退款状态 1:申请退款，2:退款完成，3：退款关闭，4：退款失败
                        if (orderBean.getRefund_state() > 0 && orderBean.getRefund_state() != 3) {
                            tv_order_state_back.setVisibility(View.VISIBLE);
                            tv_order_state_back.setText(ProductUtil.showRefundState(orderBean.getRefund_state()));
                        } else {
                            tv_order_state_back.setVisibility(View.GONE);
                        }
                        ll_show_opera_data.setVisibility(View.VISIBLE);
                        tv_order_list_delete.setVisibility(View.VISIBLE);
                        tv_order_list_logistic.setVisibility(View.GONE);
                        tv_order_list_pay.setVisibility(View.GONE);
                        break;
                    // 发货状态
                    case 4:// 待发货
                    case 6:// 待配送
                        tv_order_pay_state.setVisibility(View.VISIBLE);
                        tv_order_pay_state.setText(orderBean.getState() == 4 ? "待发货" : "待配送");
                        tv_order_pay_state.setTextColor(BaseColor.color_main);
                        // 退款状态 1:申请退款，2:退款完成，3：退款关闭，4：退款失败
                        if (orderBean.getRefund_state() > 0 && orderBean.getRefund_state() != 3) {
                            tv_order_state_back.setVisibility(View.VISIBLE);
                            tv_order_state_back.setText(ProductUtil.showRefundState(orderBean.getRefund_state()));
                        } else {
                            tv_order_state_back.setVisibility(View.GONE);
                        }
                        tv_order_list_delete.setVisibility(View.GONE);
                        tv_order_list_logistic.setVisibility(View.GONE);
                        tv_order_list_pay.setVisibility(View.GONE);
                        ll_show_opera_data.setVisibility(View.GONE);
                        break;
                    // 自取
                    case 5:// 待领取
                        tv_order_pay_state.setVisibility(View.VISIBLE);
                        tv_order_pay_state.setText("待领取");
                        tv_order_pay_state.setTextColor(BaseColor.color_main);
                        if (orderBean.getRefund_state() > 0 && orderBean.getRefund_state() != 3) {
                            tv_order_state_back.setVisibility(View.VISIBLE);
                            tv_order_state_back.setText(ProductUtil.showRefundState(orderBean.getRefund_state()));
                        } else {
                            tv_order_state_back.setVisibility(View.GONE);
                        }
                        tv_order_list_delete.setVisibility(View.GONE);
                        tv_order_list_logistic.setVisibility(View.VISIBLE);
                        tv_order_list_logistic.setText("导航到店");
                        tv_order_list_pay.setVisibility(View.GONE);
                        ll_show_opera_data.setVisibility(View.VISIBLE);
                        break;
                    // 发了货等待收货
                    case 8: // 已配送
                    case 7: // 待收货
                    case 9: // 已发货
                        tv_order_pay_state.setVisibility(View.VISIBLE);
                        tv_order_pay_state.setText("待收货");
                        tv_order_pay_state.setTextColor(BaseColor.color_main);
                        if (orderBean.getRefund_state() > 0 && orderBean.getRefund_state() != 3) {
                            tv_order_state_back.setVisibility(View.VISIBLE);
                            tv_order_state_back.setText(ProductUtil.showRefundState(orderBean.getRefund_state()));
                        } else {
                            tv_order_state_back.setVisibility(View.GONE);
                        }
                        tv_order_list_delete.setVisibility(View.GONE);
                        if (orderBean.getState() != 8) {
                            tv_order_list_logistic.setVisibility(View.VISIBLE);
                            tv_order_list_logistic.setText("查看物流");
                        } else {
                            tv_order_list_logistic.setVisibility(View.GONE);
                        }
                        tv_order_list_pay.setVisibility(View.VISIBLE);
                        tv_order_list_pay.setText("确认收货");
                        ll_show_opera_data.setVisibility(View.VISIBLE);
                        break;
                    case 10: // 已完成
                        tv_order_pay_state.setVisibility(View.VISIBLE);
                        tv_order_pay_state.setText("已完成");
                        tv_order_pay_state.setTextColor(BaseColor.color_666666);
                        if (orderBean.getRefund_state() > 0 && orderBean.getRefund_state() != 3) {
                            tv_order_state_back.setVisibility(View.VISIBLE);
                            tv_order_state_back.setText(ProductUtil.showRefundState(orderBean.getRefund_state()));
                        } else {
                            tv_order_state_back.setVisibility(View.GONE);
                        }
                        tv_order_list_delete.setVisibility(View.VISIBLE);
                        tv_order_list_logistic.setVisibility(View.GONE);
                        tv_order_list_pay.setVisibility(View.GONE);
                        ll_show_opera_data.setVisibility(View.VISIBLE);
                        break;
                    default:
                        break;
                }
                viewHolder.getConvertView().setOnClickListener(new OnNoDoubleClickListener() {
                    @Override
                    protected void onNoDoubleClick(View v) {
                        Bundle orderDetails = new Bundle();
                        orderDetails.putLong(Constants.INP_ORDER_ID, orderBean.getOrder_id());
                        openActivity(MallOrderDetailsActivity.class, orderDetails);
                    }
                });
                viewHolder.setOnClickListener(R.id.tv_order_state_back, new OnNoDoubleClickListener() {
                    @Override
                    protected void onNoDoubleClick(View v) {
                        // 查看退款状态 // 退款状态 1:申请退款，2:退款完成，3：退款关闭，4：退款失败
                        if (orderBean.getRefund_state() == 1 || orderBean.getRefund_state() == 2 || orderBean.getRefund_state() == 4) {
//                            Bundle bundle = new Bundle();
//                            bundle.putLong(Constants.INP_ORDER_REFUND_ID, orderBean.getOrder_refund_id());
//                            openActivity(SaleServiceDetailActivity.class, bundle);
                        }
                    }
                });
                viewHolder.setOnClickListener(R.id.tv_order_list_delete, new OnNoDoubleClickListener() {
                    @Override
                    protected void onNoDoubleClick(View v) {
                        // 删除订单只有2.3.10
                        setDialog(position, orderBean.getOrder_id(), "确定删除此订单？").show();
                    }
                });
                viewHolder.setOnClickListener(R.id.tv_order_list_logistic, new OnNoDoubleClickListener() {
                    @Override
                    protected void onNoDoubleClick(View v) {
                        switch (orderBean.getState()) {
                            // 导航
                            case 7:
                            case 8:
                            case 9:
                                // 查看物流
                                Bundle bundle = new Bundle();
                                bundle.putLong(LogisticsDetailsActivity.INP_ORDER_LOGISTICS_NUM, orderBean.getOrder_id());
                                openActivity(LogisticsDetailsActivity.class, bundle);
                                break;
                        }
                    }
                });
                viewHolder.setOnClickListener(R.id.tv_order_list_pay, new OnNoDoubleClickListener() {
                    @Override
                    protected void onNoDoubleClick(View v) {
                        // 确认收货和支付
                        jumpActviity(orderBean, position);
                    }
                });
            }
        };
        rv_mall_order.setAdapter(mRvOrderAdapter);
    }

    /**
     * 跳转
     *
     * @param orderBean
     * @param position
     */
    private void jumpActviity(MallOrderBean orderBean, int position) {
        Bundle bundle = new Bundle();
        switch (orderBean.getState()) {
            case 1:
                bundle.putParcelable(PayOrderActivity.INP_PAY_ORDER, orderBean);
                bundle.putInt(PayOrderActivity.INP_PAY_JUMP_TYPE, 2);
                openActivity(PayOrderActivity.class, bundle);
                break;
            case 7:
            case 8:
            case 9:
                // 收货：
                if (ProductUtil.isSubmitProduct(orderBean)) {
                    NormalAlertDialog normalAlertDialog = new NormalAlertDialog.Builder(context)
                            .setButtonTextSize(14)
                            .setContentText("是否确认收货")
                            .setContentTextSize(14)
                            .setTitleVisible(false)
                            .setLeftButtonText("取消")
                            .setRightButtonText("确定")
                            .setRightButtonTextColor(R.color.color_main)
                            .setLeftButtonTextColor(R.color.color_333333)
                            .setContentTextColor(R.color.color_333333)
                            .setOnclickListener(new DialogOnClickListener() {
                                @Override
                                public void clickLeftButton(View view) {

                                }

                                @Override
                                public void clickRightButton(View view) {
                                    startProgressDialog();
                                    FormBodys formBodys = new FormBodys.Builder()
                                            .add("order_id", orderBean.getOrder_id())
                                            .build();
                                    mPresenter.onOrderReceipt(formBodys, position);
                                }
                            }).build();
                    normalAlertDialog.show();
                } else {
                    showShortToast("售后处理中,不可确认收货");
                }
                break;
        }
    }


    /**
     * 删除订单的dialog
     *
     * @param position
     * @param order_id
     * @param title
     * @return
     */
    private NormalAlertDialog setDialog(int position, long order_id, String title) {
        NormalAlertDialog normalAlertDialog = new NormalAlertDialog.Builder(context)
                .setButtonTextSize(14)
                .setContentText(title)
                .setContentTextSize(14)
                .setTitleVisible(false)
                .setContentTextColor(R.color.color_333333)
                .setOnclickListener(new DialogOnClickListener() {
                    @Override
                    public void clickLeftButton(View view) {
                    }

                    @Override
                    public void clickRightButton(View view) {
                        deteleData(position, order_id);
                    }
                }).build();
        return normalAlertDialog;
    }


    private void initRv() {
        setRefreshLayout(srl_mall_order);
        srl_mall_order.setRefreshHeader(new RefreshHeaderView(context).getHeaderStyleStaffF4());
        srl_mall_order.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNum++;
                fetchOrderList();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNum = 1;
                fetchOrderList();
            }
        });
    }

    /**
     * 获取订单数据
     */
    private void fetchOrderList() {
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("id", 0);
        formBodys.add("state", order_state);
        formBodys.add("page", pageNum);
        formBodys.add("per_page", 10);
        mPresenter.onOrderList(formBodys.build());
    }

    /**
     * 删除订单
     *
     * @param position
     * @param order_id
     */
    private void deteleData(int position, long order_id) {
        startProgressDialog();
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("id", 0);
        formBodys.add("order_id", order_id);
        mPresenter.onDeleteOrder(formBodys.build(), position);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mFragment = null;
    }

    private void setEmpty() {
        if (mOrder.size() == 0) {
            /**
             * 0 = 从我的订单跳转（默认） 1.待付款 2.已取消 3.服务中 4.已完成 5.已关闭
             */
            String orderData;
            if (order_state == 1) {
                orderData = "待付款";
            } else if (order_state == 2) {
                orderData = "已取消";
            } else if (order_state == 3) {
                orderData = "服务中";
            } else if (order_state == 4) {
                orderData = "已完成";
            } else if (order_state == 5) {
                orderData = "已关闭";
            } else {
                orderData = "相关";
            }
            ltip_mall_order.setLoadingTip(LoadingTip.LoadStatus.empty);
            ltip_mall_order.setTips("您目前没有" + orderData + "的订单哦~");
        } else {
            ltip_mall_order.setLoadingTip(LoadingTip.LoadStatus.finish);
        }
    }

    @Override
    public void showMessage(String message, String method) {
        stopProgressDialog();
        showShortToast(message);
    }

    @Override
    public void showErrorView(String msg) {
        showErrorView(msg, ltip_mall_order);
        ltip_mall_order.setOnReloadListener(view -> {
            ltip_mall_order.setLoadingTip(LoadingTip.LoadStatus.loading);
            fetchOrderList();
        });
    }

    @Override
    public void onOrderList(ListPageBean<MallOrderBean> orderList) {
        ltip_mall_order.setLoadingTip(LoadingTip.LoadStatus.finish);
        if (pageNum == 1) {
            mOrder.clear();
            srl_mall_order.finishRefresh();
        } else {
            srl_mall_order.finishLoadMore();
        }
        mOrder.addAll(orderList.getList());
        mRvOrderAdapter.notifyDataSetChanged();
        if (orderList.getList().size() < 10) {
            srl_mall_order.setEnableLoadMore(false);
        } else {
            srl_mall_order.setEnableLoadMore(true);
        }
        setEmpty();
    }

    @Override
    public void onDeleteOrder(String msg, int position) {
        stopProgressDialog();
        showShortToast(msg);
        mOrder.remove(position);
        mRvOrderAdapter.notifyDataSetChanged();
        setEmpty();
    }

    @Override
    public void onOrderReceipt(String msg, int position) {
        // 确认收货
        stopProgressDialog();
        showShortToast(msg);
        if (order_state == 0) {
            mOrder.get(position).setState(10);
            mRvOrderAdapter.notifyItemChanged(position);
        } else {
            RxBus.getDefault().postSticky(new MallOrderListBus(3));
        }
    }

    @Override
    public void onOrderCancel(String msg, int position) {

    }
}